<?php
namespace Ucmaim\Model;
use Think\Model;


class GoodsCategoryModel extends Model{

    // 获取分类列表
    public function get($pid = 0, $goods_type = false,$limit){
        $map['gc_pid'] = $pid;
	    if($limit>0){
		    $category = $this->where($map)->order("gc_sort desc")->limit($limit)->select();
	    }else{
		    $category = $this->where($map)->order("gc_sort desc")->select();
	    }
        if($goods_type && !empty($category)){
            $M = M('goods_type');
            foreach( $category as $k => $v ){
                $map['gc_id'] = $v['gc_id'];
                $options = $M->field('type_id, type_name')->where($map)->select();
                $category[$k]['types'] = $options;
            }
        }
        return $category;
    }

    /**
     * 从分类关系查询完整的区服信息
     *
     * @param $data
     * @return array()
     */
    public function getRelation($data = array()){
        $self = array(
            'gc_id'   => $data['gc_id'],
            'gc_name' => $data['gc_name']
        );
        $map = [];
        $relation = extraCharFilter($data['gc_relation']);
        $map['gc_id'] = array('IN', $relation);
        $result = $this->where($map)->select();
        $result[] = $self;
        $data['goods_relation'] = $result;

        return $data;
    }

    //由id查询分类
    public function getOne($id){
        $map['gc_id'] = (int)$id;
        $result = $this->where($map)->find();
        return $result;
    }

    //递归返回分类数组
    function RecursiveCategory(){
        $data = $this->field('gc_id AS value, gc_name AS name, gc_pid AS pid')->select();
        return $this->_arrayPidProcess($data,array(),'0');
    }

    //数组递归
    private function _arrayPidProcess($data, $res=array(), $pid='0'){
        foreach ($data as $k => $v){
            if($v['pid'] == $pid){
                $res[$v['value']] = $v;
                $child = $this->_arrayPidProcess($data, array(), $v['value']);
                if( $child ){
                    $res[$v['value']]['child']=$child;
                }
            }
        }
        return $res;
    }
}